#include "chatserver.hpp"
#include "chatservice.hpp"

#include <iostream>
#include <csignal> // for sigaction()

using namespace std;

// 处理服务器ctrl + c 结束后， 重置user的状态信息 需要导入业务头文件chatservice.hpp
void resetHandler(int signum)
{
    ChatService::getInstance()->resetState();
    exit(0);
}

int main(int argc, char **argv)
{
    if (argc < 3)
    {
        std::cerr << "command invalid! xampl: ./ChatServer 127.0.0.1 6000" << std::endl;
        exit(-1);
    }

    // 解析通过命令行参数传递的ip 和 port
    char * ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    struct sigaction newAct;
    // 设置信号处理器和启用对阻塞操作的自动重启
    memset(&newAct, 0, sizeof(newAct));
    newAct.sa_handler = &resetHandler;
    newAct.sa_flags = SA_RESTART;
    if (sigaction(SIGINT, &newAct, NULL) == -1)  // 服务器接收到ctrl + c 就执行service::resetState()业务
    {
        perror("sigaction");
        return -1;
    }

    EventLoop loop;
    InetAddress addr(ip, port);
    ChatServer server(&loop, addr, "CharServer");

    server.start();
    loop.loop();

    return 0;
}